package cmd

import (
	"bytes"
	"github.com/dwbmio/ding-cli/pkg"
	"github.com/spf13/cobra"
	"github.com/wonderivan/logger"
	"os"
	"os/exec"
	"runtime"
)

type RunParams struct {
	projConf *ProjConf
}

type RunHandler struct {
	p RunParams
}

func (handle *RunHandler) Run(p RunParams) error {
	handle.p = p
	conf := handle.p.projConf
	//gen conf
	handler := GenconfHandler{}
	handler.Run(GenconfParams{rootPath: conf.RootPath, platform: runtime.GOOS, serverFiles: conf.Servers})
	//run
	var _, err = os.Stat(srcPath)
	if os.IsNotExist(err) {
		return pkg.NewDError(104)
	}
	ret := exec.Command("openresty", "-c", nginxConf)

	var stdout bytes.Buffer
	var stderr bytes.Buffer
	ret.Stdout = &stdout
	ret.Stderr = &stderr
	err1 := ret.Run()
	if err1 != nil {
		return pkg.NewDError(105, stderr.String())
	}
	if len(stderr.String()) > 0 {

		logger.Warn(stderr.String())
		logger.Info("ding run suc with **warn**!")
		return nil
	}
	logger.Info("ding run suc!")
	return nil
}

func Run() *cobra.Command {
	var runCmd = &cobra.Command{
		Use:     "run",
		Version: "v0.0.1",
		Short:   UsageGenConf,
		Long:    UsageGenConf,
		Run: func(cmd *cobra.Command, args []string) {
			pwd, _ := os.Getwd()
			conf, err := CheckProjConf(pwd)
			if err != nil {
				logger.Error(err.Error())
				return
			}
			var handle = &RunHandler{}
			err = handle.Run(RunParams{projConf: conf})
			if err != nil {
				logger.Error(err)
				return
			}
			logger.Info("Init suc!")
		},
	}

	runCmd.Flags().StringVarP(&rootPath, "path", "p", "", "the rootPath for run ding")
	return runCmd
}
